package com.tomorrow.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

//进行全局过滤器的配置设置

@Order(1) //设置当前过滤器的等级 方法一
@Component //把当前过滤器bean对象放入spring容器
public class AuthorizeFilter implements GlobalFilter/*, Ordered */{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // exchange
        // chain

        //获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        //获取第一个出现的key为author的参数的值
        String authorization = queryParams.getFirst("author");

        //进行校验判断是否放行
        if("admin".equals(authorization)){
            //放行
            return chain.filter(exchange);
        }

        //校验失败,无访问权限，进行拦截
        //设置禁止访问的状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //结束过滤请求的处理
        return exchange.getResponse().setComplete();
    }

    /*@Override //设置当前过滤器的等级 方法二，实现 Ordered 接口，重写getOrder()方法，设置等级
    public int getOrder() {
        return 1;
    }*/
}

